﻿using System;
using System.ComponentModel;
using Alderamin.Core;

namespace Alderamin
{
    public class MainViewModel : INotifyPropertyChanged
    {
        private AlderaminClientProxy _localProxy;

        public ClientProxyConfiguration CurrentConfig { get; set; }

        private bool _isProxyStopped;
        /// <summary>
        /// Gets the value indicates that whether the local proxy has stopped
        /// </summary>
        /// <returns></returns>
        public bool IsProxyStopped
        {
            get
            {
                return _isProxyStopped;
            }
            private set
            {
                _isProxyStopped = value;
                this.NotifyPropertyChanged("IsProxyStopped");
            }
        }

        public MainViewModel()
        {
            _isProxyStopped = true;
            // Retreive the last saved configuration
            this.CurrentConfig = ClientProxyConfiguration.Synchronized(new ClientProxyConfiguration()) as ClientProxyConfiguration;
        }

        /// <summary>
        /// Starts or stops the local proxy
        /// </summary>
        public void ChangeProxyState()
        {
            if (null == _localProxy)
            {
                _localProxy = new AlderaminClientProxy(this.CurrentConfig);
            }
            if (_localProxy.IsStarted)
            {
                // Stop the proxy
                _localProxy.Stop();
            }
            else
            {
                // Reset the configuration and start the proxy
                _localProxy.Configuration = this.CurrentConfig;
                _localProxy.Start();
                this.CurrentConfig.Save();
            }
            this.IsProxyStopped = !_localProxy.IsStarted;
        }

        #region INotifyPropertyChanged
        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged(String info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }
        #endregion

    }
}